import { IMenu } from './menuAdmin'
import router from '@renderer/plugins/router'
import { ref } from 'vue'
import useStorage from './useStorage'
import { CacheEnum } from '@renderer/enum/CacheEnum'
const storage = useStorage()
const menu_type = await storage.get(CacheEnum.MENU_TYPE)
class Menu {
  public menus = ref<IMenu[]>([])
  public history = ref<IMenu[]>([])

  constructor() {
    this.menus.value = this.getMenuByRoute()
  }
  toggleParentMenu(menu: IMenu) {
    if (menu.isClick) {
      menu.isClick = false
      return
    }
    this.menus.value.forEach((m) => {
      m.children?.forEach((mc) => {
        mc.isClick = false
      })
      if (m == menu) {
        m.isClick = true
      } else {
        m.isClick = false
      }
    })
  }
  setCurrentMenu(routeName: string, pageQuery: { [key: string]: string }) {
    this.menus.value.forEach((m) => {
      m.isClick = false
      m.children?.forEach((c) => {
        c.isClick = false
        if (c.route == routeName) {
          m.isClick = true
          c.isClick = true
          window.api.closeWindow('findSearch', 'destroy')
          router.push({ name: c.route, query: pageQuery })
        }
      })
    })
  }
  getMenuByRoute() {
    return router
      .getRoutes()
      .filter(
        (route) =>
          route.children.length && (route.meta.menu?.isType == menu_type || route.meta.menu?.isType == 'public'),
      )
      .sort((a, b) => {
        return (b.meta.menu?.order ?? 0) - (a.meta.menu?.order ?? 0)
      })
      .map((route) => {
        let menu: IMenu = { ...route.meta?.menu }
        menu.children = route.children
          .filter((route) => route.meta?.menu)
          .map((route) => {
            return { ...route.meta?.menu, route: route.name }
          }) as IMenu[]
        return menu
      })
      .filter((menu) => menu.children?.length) as IMenu[]
  }
}

export default new Menu()
